import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home/Home.vue'

const SearchPopup = () => import('@/components/SearchPopup.vue')
const Topic = () => import('@/views/Topic.vue')
const Category = () => import('@/views/Category.vue')
const Cart = () => import('@/views/Cart.vue')
const User = () => import('@/views/User.vue')
const ProductDetails = () => import('@/components/ProductDetails.vue')
const Channel_Cate = () => import('@/views/Home/Channel_Cate.vue')
const Brand = () => import('@/views/Home/Brand.vue')
const Empty = () => import('@/components/Empty.vue')
Vue.use(VueRouter)


// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}



const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [{
      path: '/home/popup',
      name: 'SearchPopup',
      component: SearchPopup
    }],
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/topic',
    name: 'Topic',
    component: Topic,
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: Category,
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: User,
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/productdetails',
    name: 'ProductDetails',
    component: ProductDetails,
  },
  {
    path: '/channel',
    name: 'Channel_Cate',
    component: Channel_Cate,
  },
  {
    path: '/brand',
    name: 'Brand',
    component: Brand,
  },
  {
    path: '/empty',
    name: 'Empty',
    component: Empty,
  },

]

const router = new VueRouter({
  routes,


})

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token');
  if (to.path === '/cart') {
    if (token) {
      next()
    } else {
      //路由文件，没有this,undefinded。
      //this.$toast.fail('请先登录！');
      //然后第三方组件在vue的原型上挂载了对应方法。这里有引入Vue。所以
      Vue.prototype.$toast.fail('请先登录！');
      //定时器跳转登陆页面
      setTimeout(() => {
        next('/user')
      }, 1000)
      return
    }
  }
  next()
})






export default router